//package com.example.userdemo.service.impl;
//
//import com.example.userdemo.entity.LoginUser;
//import com.example.userdemo.entity.SysUser;
//import com.example.userdemo.service.LoginService;
//import com.example.userdemo.util.JwtUtil;
//import com.example.userdemo.util.RedisCache;
//import com.example.userdemo.util.Response;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.Resource;
//import java.util.HashMap;
//import java.util.Objects;
//
//@Service
//public class LoginServiceImpl implements LoginService {
//
//    @Resource
//    private AuthenticationManager authenticationManager;
//    @Resource
//    private RedisCache redisCache;
//
//    @Override
//    public Response login(SysUser user) {
//        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
//        // 调用authenticate方法认证时
//        // 会执行UserDetailsServiceImpl中的loadUserByUsername方法
//        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
//        if(Objects.isNull(authenticate)){
//            throw new RuntimeException("用户名或密码错误");
//        }
//        //使用userid生成token
//        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
//        String userId = loginUser.getUser().getId().toString();
//        String jwt = JwtUtil.createJWT(userId);
//        //authenticate存入redis
//        redisCache.setCacheObject("login:"+userId,loginUser);
//        //把token响应给前端
//        HashMap<String,String> map = new HashMap<>();
//        map.put("token",jwt);
//        return new Response("200","登陆成功",map);
//    }
//
//    // 退出登录业务
//    @Override
//    public Response logout() {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        Long userid = loginUser.getUser().getId();
//        redisCache.deleteObject("login:"+userid);
//        return new Response("200","退出成功");
//    }
//
//}
//
//
